package cn.neusoft.controller;

import cn.neusoft.domain.Allocate;
import cn.neusoft.domain.Commodity_Warehouse;
import cn.neusoft.domain.Order1;
import cn.neusoft.domain.Task;
import cn.neusoft.enums.*;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.feignClients.CommodityFeignClient;
import cn.neusoft.feignClients.CustomerFeignClient;
import cn.neusoft.feignClients.DeliveryFeignClient;
import cn.neusoft.query.AllocationQuery;
import cn.neusoft.service.Commodity_WarehouseService;
import cn.neusoft.service.WarehouseService;
import cn.neusoft.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Description:仓库管理的controller
 * @Author: 邢旭升
 * @Date: 2023/6/26 下午 02:08
 **/
@RestController
@RequestMapping(value = "/Warehouse",produces = "application/json;charset=utf-8")
@Api(value = "仓库管理模块的API", description = "业务逻辑代码")
public class Commodity_WarehouseController {
    private final Commodity_WarehouseService commodityWarehouseService;


    @Autowired
    public Commodity_WarehouseController(Commodity_WarehouseService commodityWarehouseService) {
        this.commodityWarehouseService = commodityWarehouseService;
    }
    @Autowired
    DeliveryFeignClient deliveryFeignClient;

    @Autowired
    CommodityFeignClient commodityFeignClient;

    @Autowired
    WarehouseService warehouseService;

    @Autowired
    CustomerFeignClient customerFeignClient;

    @ApiOperation(value = "获取指定仓库的库存量")
    @GetMapping("getWarehouseStock/{warehouseId}")
    public java.lang.Long GetWarehouseStock(@PathVariable("warehouseId") java.lang.Long warehouseId) {
        return commodityWarehouseService.GetWarehouseStock(warehouseId);
    }

    @ApiOperation(value = "获取指定仓库指定商品的库存量")
    @GetMapping("/{commodityId}/{warehouseId}")
    public ResultBean getCommodityWarehouse(@PathVariable("commodityId") String commodityId,
                                                     @PathVariable("warehouseId") java.lang.Long warehouseId) {
        Commodity_Warehouse commodityWarehouse = commodityWarehouseService.getCommodityWarehouse(commodityId, warehouseId);
        return ResultBean.success(commodityWarehouse);
    }



    @ApiOperation(value = "入库")
    @PostMapping("/InWarehouse")
    public ResultBean updateCommodityWarehouse(@RequestBody Allocate allocate) {
        Long Inid = allocate.getIn_id();
        Long amount = allocate.getAmount();
        String commodity_id = allocate.getCommodity_id();

        Commodity_Warehouse commodityWarehouse = new Commodity_Warehouse(commodity_id,Inid,amount,0L);

        Commodity_Warehouse commodityWarehouse1 = commodityWarehouseService.getCommodityWarehouse(commodity_id, Inid);
        if(commodityWarehouse1 == null){
            commodityWarehouseService.addCommodityWarehouse(commodityWarehouse);
        }else {
            commodityWarehouseService.updateCommodityWarehouse(commodityWarehouse);
            allocate.setDel_flag(AllocateState.FINISHED.getCode());
            deliveryFeignClient.updateAllocate(allocate);
            //将补货的订单状态修改
            if(allocate.getRemark().equals(AllocateType.REPLENISHMENT.getCode())){
                Order1 order1 = new Order1();
                order1.setOrder_id(allocate.getOrder_id());
                order1.setOrder_status("1");
                customerFeignClient.updateOrderStatus(order1);
            }
            //换货到分站以后自动变成终点为中央仓库的出库调拨单
            if(allocate.getRemark().equals(AllocateType.EXCHANGE.getCode()) && Objects.equals(allocate.getOut_id(), -1L)){
                allocate.setOut_id(Inid);
                allocate.setDel_flag(AllocateState.NOT_SHIPPED.getCode());
                allocate.setIn_id(Warehouse.CENTER_WAREHOUSE.getCode());
                deliveryFeignClient.updateAllocate(allocate);
            }else{
                if(allocate.getRemark().equals(AllocateType.EXCHANGE.getCode())) {
                    if(Objects.equals(allocate.getOut_id(),Warehouse.CENTER_WAREHOUSE.getCode())){
                        System.out.println("进入条件==================================================================");
                        Task task = new Task();
                        task.setTask_id(allocate.getTask_id());
                        task.setTask_state(TaskState.ASSIGNABLE.getCode());
                        deliveryFeignClient.update(task);
                    }
                }
            }
            if(allocate.getRemark().equals(AllocateType.TRANSFER.getCode())){
                if(Objects.equals(allocate.getOut_id(),Warehouse.CENTER_WAREHOUSE.getCode())){
                    Task task = new Task();
                    task.setTask_id(allocate.getTask_id());
                    task.setTask_state(TaskState.ASSIGNABLE.getCode());
                    deliveryFeignClient.update(task);
                }
            }


        }

        System.out.println("===================进入他妈的请求========================================");
        System.out.println(allocate.getRemark());
        System.out.println(allocate.getOut_id());
        System.out.println(Objects.equals(allocate.getOut_id(),Warehouse.CENTER_WAREHOUSE.getCode()));
        System.out.println(allocate.getRemark().equals(AllocateType.EXCHANGE.getCode()) || allocate.getRemark().equals(AllocateType.TRANSFER.getCode()));



        if(allocate.getRemark().equals(AllocateType.RETURN.getCode())){
            Task task = new Task();
            task.setTask_id(allocate.getTask_id());
            task.setTask_state(TaskState.PICKED_UP.getCode());
            deliveryFeignClient.update(task);
        }




        return ResultBean.success();
    }
    @ApiOperation(value = "出库")
    @PostMapping("/OutWarehouse")
    public ResultBean outWarehouse(@RequestBody Allocate allocate){
        java.lang.Long outId = allocate.getOut_id();
        java.lang.Long amount = allocate.getAmount();
        String commodity_id = allocate.getCommodity_id();

        Commodity_Warehouse commodityWarehouse1 = commodityWarehouseService.getCommodityWarehouse(commodity_id, outId);
        if(commodityWarehouse1.getAmount() < amount){
            return ResultBean.error(AppExceptionCodeMsg.LogicalWrong);
        }

        System.out.println("=========打印自动补货逻辑参数=============");
        System.out.println(amount);
        System.out.println(commodityWarehouse1.getAmount());
        System.out.println(warehouseService.selectById(outId).getWarn_value());


        //自动补货的逻辑,补货供货商火速出货,只有中央库房缺货才会自动补货
        if(commodityWarehouse1.getAmount() - amount < warehouseService.selectById(outId).getWarn_value() && Objects.equals(outId, Warehouse.CENTER_WAREHOUSE.getCode())){
            Allocate allocate1 = new Allocate();
            allocate1.setIn_id(Warehouse.CENTER_WAREHOUSE.getCode());
            allocate1.setCommodity_id(commodity_id);
            allocate1.setAmount(amount);
            allocate1.setRemark(AllocateType.REPLENISHMENT.getCode());
            allocate1.setDel_flag(AllocateState.SHIPPED.getCode());
            deliveryFeignClient.AddAllocateAnyway(allocate1);
        }

        Commodity_Warehouse commodityWarehouse;
        //当退货和换货的时候不算商品的占用状态，因为只是走一个过场，不是真正的商品占用
        if(allocate.getRemark().equals(AllocateType.RETURN.getCode()) || allocate.getRemark().equals(AllocateType.EXCHANGE.getCode())){
            commodityWarehouse = new Commodity_Warehouse(commodity_id,outId,-amount,0L);
        }else{
            commodityWarehouse = new Commodity_Warehouse(commodity_id,outId,-amount,-amount);
        }

        commodityWarehouseService.updateCommodityWarehouse(commodityWarehouse);

        if(Objects.equals(allocate.getOut_id(), Warehouse.CENTER_WAREHOUSE.getCode())&&allocate.getRemark().equals("3")){
            allocate.setDel_flag("2");
        }else {
            allocate.setDel_flag("1");
        }


        deliveryFeignClient.updateAllocate(allocate);
        return ResultBean.success();
    }

    @PostMapping("/ReturnedInWarehouse")
    public ResultBean ReturnedInWarehouse(@RequestBody Allocate allocate){
        Long Inid = allocate.getIn_id();
        Long amount = allocate.getAmount();
        String commodity_id = allocate.getCommodity_id();

        Commodity_Warehouse commodityWarehouse = new Commodity_Warehouse(commodity_id,Inid,amount,0L);

        Commodity_Warehouse commodityWarehouse1 = commodityWarehouseService.getCommodityWarehouse(commodity_id, Inid);
        if(commodityWarehouse1 == null){
            commodityWarehouseService.addCommodityWarehouse(commodityWarehouse);
        }else {
            commodityWarehouseService.updateCommodityWarehouse(commodityWarehouse);
        }


        if(Inid != Warehouse.CENTER_WAREHOUSE.getCode()){
            allocate.setOut_id(Inid);
            allocate.setIn_id(Warehouse.CENTER_WAREHOUSE.getCode());
            allocate.setDel_flag(AllocateState.NOT_SHIPPED.getCode());
        }else {
            allocate.setDel_flag(AllocateState.FINISHED.getCode());
        }
        deliveryFeignClient.updateAllocate(allocate);

        //当退货到分站时任务单的状态
        Task task = new Task();
        task.setTask_id(allocate.getTask_id());
        task.setTask_state(TaskState.PICKED_UP.getCode());
        deliveryFeignClient.update(task);


        //更新退货状态
//        Order1 order1 = new Order1();
//        order1.setOrder_id(allocate.getOrder_id());
//        order1.setOrder_status(OrderStatus.FINISHED.getCode());
//        customerFeignClient.updateOrderStatus(order1);


        return ResultBean.success();
    }


    @ApiOperation(value = "删除商品")
    @PostMapping("/deleteCommodityWarehouse")
    public ResultBean deleteCommodityWarehouse(@RequestBody Commodity_Warehouse commodityWarehouse) {
        int i = commodityWarehouseService.deleteCommodityWarehouse(commodityWarehouse.getCommodity_id(), commodityWarehouse.getWarehouse_id());
        return ResultBean.success(i);
    }

    @GetMapping("/getCommodity/{id}")
    public ResultBean getById(@PathVariable("id") String id){
        System.out.println(id);
        return commodityFeignClient.getById(id);
    }

    @PostMapping("/getAllocateByPage")
    public ResultBean getAllocateByPage(@RequestBody AllocationQuery query){
        return deliveryFeignClient.FindAllocateByPages(query);
    }

    @PostMapping("/findReturnedAllocate")
    public ResultBean findReturnedAllocate(@RequestBody AllocationQuery allocationQuery){
        return deliveryFeignClient.findReturnedAllocate(allocationQuery);
    }


    @PostMapping("/takeCommodity")
    public ResultBean TakeCommodity(@RequestBody Task task){
        java.lang.Long out_id = task.getWarehouse_id();
        String commodity_id = task.getCommodity_id();
        java.lang.Long amount = task.getAmount();
        String order_id = task.getOrder_id();

        Commodity_Warehouse commodityWarehouse1 = commodityWarehouseService.getCommodityWarehouse(commodity_id, out_id);
        if(commodityWarehouse1.getAmount() < amount){
            return ResultBean.error(AppExceptionCodeMsg.LogicalWrong);
        }
        Commodity_Warehouse commodityWarehouse = new Commodity_Warehouse();
        commodityWarehouse.setCommodity_id(commodity_id);
        commodityWarehouse.setWarehouse_id(out_id);
        commodityWarehouse.setAmount(-amount);
        commodityWarehouseService.updateCommodityWarehouse(commodityWarehouse);
        //更新任务单的状态
        task.setTask_state(TaskState.PICKED_UP.getCode());
        deliveryFeignClient.update(task);
        //更新订单的状态
        Order1 order1 = new Order1();
        order1.setOrder_id(task.getOrder_id());
        order1.setOrder_status(OrderStatus.PICKED_UP.getCode());

        customerFeignClient.updateOrderStatus(order1);

        return ResultBean.success();

    }


}
